#include "googleapi.h"

GoogleApi::GoogleApi()
{
}


GoogleApi::~GoogleApi()
{
}

QString GoogleApi::translate(const QString &src, const QString &dest, const QString &txt)
{
    QByteArray query = "v=1.0&key=AIzaSyC5WOTT5MQK9UKJihZLLAnkOqFa9O7SXg8";
    query += "&langpair=" + src.toLatin1() + "%7C" + dest.toLatin1();
    query += "&q=" + txt;
    QUrl url("http://ajax.googleapis.com/ajax/services/language/translate");
    /* v2 https api openssl needed
    QByteArray query = "https://www.googleapis.com/language/translate/v2";
    query += "?key=AIzaSyC5WOTT5MQK9UKJihZLLAnkOqFa9O7SXg8";
    query += "&source=" + src.toLatin1() + "&target=" + dest.toLatin1();
    query += "&q=" + txt + "&callback=translateText";
    QUrl url(query);
    */
    QNetworkRequest req(url);
    QNetworkAccessManager manager;
    QEventLoop loop;
    connect(&manager, SIGNAL(finished(QNetworkReply*)), &loop, SLOT(quit()));
    QTimer::singleShot(2000, &loop, SLOT(quit()));
    QNetworkReply *translateReply = manager.post(req, query);
//    QNetworkReply *reply = manager.get(req); //v2 api
    loop.exec();
    const QByteArray rawdata = translateReply->readAll();
    QString out(QString::fromUtf8(rawdata.data()));
    int idx1 = out.indexOf("translatedText");
//    idx1 += 18; //v2 api
    idx1 += 17;
    int idx2 = out.indexOf("\"", idx1);
    out = out.mid(idx1, idx2 - idx1);
    return out;
}

void GoogleApi::texttospeech(const QString &lng, const QString &txt)
{
    QString urlstring("http://translate.google.com/translate_tts");
    urlstring += "?tl=" + lng + "&q=" + txt;
    QUrl url(urlstring);
    Phonon::MediaObject *speechMediaObject = Phonon::createPlayer(Phonon::MusicCategory, Phonon::MediaSource(url));
    speechMediaObject->play();
    connect(speechMediaObject, SIGNAL(finished()), speechMediaObject, SLOT(deleteLater()));
}
